package utils

import (
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"golang.org/x/crypto/bcrypt"
	"leading/global"
	"leading/models"
	"time"
)

type Myclaims struct {
	User models.UserModel `json:"user"`
	jwt.RegisteredClaims
}

// 生成token
func GenerateToken(user models.UserModel) (string, error) {
	key := []byte(global.Config.Jwt.Secret)
	expireHour := global.Config.Jwt.ExpireHour
	issuer := global.Config.Jwt.Issuer
	claims := Myclaims{
		User: user,
		RegisteredClaims: jwt.RegisteredClaims{
			Issuer:    issuer,
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(expireHour) * time.Hour)),
			IssuedAt:  jwt.NewNumericDate(time.Now()),
		},
	}
	t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return t.SignedString(key)
}

// 验证token
func VerifyToken(token string) (*Myclaims, error) {
	tokenRes, err := jwt.ParseWithClaims(token, &Myclaims{}, func(t *jwt.Token) (interface{}, error) {
		return []byte(global.Config.Jwt.Secret), nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := tokenRes.Claims.(*Myclaims); ok && tokenRes.Valid {
		return claims, nil
	}
	return nil, errors.New("tokenErr")
}

// 密码加密
func EncryptPassword(password string) (string, error) {
	hasePassword, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.MinCost)
	if err != nil {
		return "", err
	}
	return string(hasePassword), nil
}

// 密码验证
func VerifyEncryptPassword(password string, hasePassword string) bool {
	err := bcrypt.CompareHashAndPassword([]byte(hasePassword), []byte(password))
	return err == nil
}
